using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SmartMedical.WinUI
{
    /// <summary>
    /// 病历书写窗体
    /// 用于医生录入患者的病历信息
    /// </summary>
    public partial class MedicalRecordForm : Form
    {
        #region 私有字段
        /// <summary>
        /// HTTP客户端，用于API调用
        /// </summary>
        private readonly HttpClient _httpClient;
        
        /// <summary>
        /// API基础地址
        /// </summary>
        private readonly string _apiBaseUrl = "http://localhost:5165";
        
        /// <summary>
        /// 患者ID
        /// </summary>
        private long _patientId;
        
        /// <summary>
        /// 患者姓名
        /// </summary>
        private string _patientName;
        #endregion

        #region 构造函数
        /// <summary>
        /// 初始化病历书写窗体
        /// </summary>
        public MedicalRecordForm()
        {
            InitializeComponent();
            _httpClient = new HttpClient();
            InitializeForm();
        }
        
        /// <summary>
        /// 初始化病历书写窗体（带患者信息）
        /// </summary>
        /// <param name="patientId">患者ID</param>
        /// <param name="patientName">患者姓名</param>
        public MedicalRecordForm(long patientId, string patientName) : this()
        {
            _patientId = patientId;
            _patientName = patientName;
            this.Text = $"病历书写 - {patientName}";
        }
        #endregion

        #region 初始化方法
        /// <summary>
        /// 初始化窗体设置
        /// </summary>
        private void InitializeForm()
        {
            // 设置窗体属性
            this.Icon = SystemIcons.Application;
            
            // 设置输入框提示文本
            SetPlaceholderTexts();
            
            // 绑定键盘事件
            this.KeyPreview = true;
            this.KeyDown += MedicalRecordForm_KeyDown;
        }
        
        /// <summary>
        /// 设置输入框的提示文本
        /// </summary>
        private void SetPlaceholderTexts()
        {
            // 为各个文本框设置提示信息
            SetTextBoxPlaceholder(txtChiefComplaint, "请输入患者的主要症状和就诊原因...");
            SetTextBoxPlaceholder(txtPresentIllness, "请详细描述患者现在疾病的发生、发展过程...");
            SetTextBoxPlaceholder(txtPastHistory, "请输入患者既往疾病史、手术史、外伤史等...");
            SetTextBoxPlaceholder(txtAllergyHistory, "请输入患者的药物过敏史、食物过敏史等...");
            SetTextBoxPlaceholder(txtPersonalHistory, "请输入患者的生活习惯、职业史、婚育史等...");
            SetTextBoxPlaceholder(txtFamilyHistory, "请输入患者家族遗传病史、家族疾病史等...");
            SetTextBoxPlaceholder(txtPhysicalExam, "请输入体格检查结果，包括生命体征、各系统检查等...");
            SetTextBoxPlaceholder(txtAuxiliaryExam, "请输入实验室检查、影像学检查等辅助检查结果...");
            SetTextBoxPlaceholder(txtTreatmentAdvice, "请输入诊断结果和治疗建议，包括用药方案、注意事项等...");
        }
        
        /// <summary>
        /// 为文本框设置提示文本
        /// </summary>
        /// <param name="textBox">文本框控件</param>
        /// <param name="placeholder">提示文本</param>
        private void SetTextBoxPlaceholder(TextBox textBox, string placeholder)
        {
            textBox.Text = placeholder;
            textBox.ForeColor = System.Drawing.Color.Gray;
            
            textBox.Enter += (s, e) =>
            {
                if (textBox.Text == placeholder)
                {
                    textBox.Text = "";
                    textBox.ForeColor = System.Drawing.Color.Black;
                }
            };
            
            textBox.Leave += (s, e) =>
            {
                if (string.IsNullOrWhiteSpace(textBox.Text))
                {
                    textBox.Text = placeholder;
                    textBox.ForeColor = System.Drawing.Color.Gray;
                }
            };
        }
        #endregion

        #region 事件处理方法
        /// <summary>
        /// 键盘按键事件处理
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">键盘事件参数</param>
        private void MedicalRecordForm_KeyDown(object sender, KeyEventArgs e)
        {
            // Ctrl+S 保存
            if (e.Control && e.KeyCode == Keys.S)
            {
                BtnSave_Click(sender, e);
                e.Handled = true;
            }
            // ESC 取消
            else if (e.KeyCode == Keys.Escape)
            {
                BtnCancel_Click(sender, e);
                e.Handled = true;
            }
        }
        
        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private async void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (!ValidateInput())
                {
                    return;
                }
                
                // 禁用按钮防止重复提交
                btnSave.Enabled = false;
                btnSave.Text = "保存中...";
                
                // 构建病历数据
                var medicalRecord = new MedicalRecordData
                {
                    PatientId = _patientId,
                    PatientName = _patientName,
                    ChiefComplaint = GetTextBoxValue(txtChiefComplaint),
                    PresentIllness = GetTextBoxValue(txtPresentIllness),
                    PastHistory = GetTextBoxValue(txtPastHistory),
                    AllergyHistory = GetTextBoxValue(txtAllergyHistory),
                    PersonalHistory = GetTextBoxValue(txtPersonalHistory),
                    FamilyHistory = GetTextBoxValue(txtFamilyHistory),
                    PhysicalExam = GetTextBoxValue(txtPhysicalExam),
                    AuxiliaryExam = GetTextBoxValue(txtAuxiliaryExam),
                    TreatmentAdvice = GetTextBoxValue(txtTreatmentAdvice),
                    CreateTime = DateTime.Now,
                    Doctor = "当前医生" // 这里应该从登录信息获取
                };
                
                // 调用API保存病历
                var result = await SaveMedicalRecordAsync(medicalRecord);
                
                if (result.Success)
                {
                    MessageBox.Show($"病历保存成功！\n病历编号：{result.RecordId}", 
                        "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show($"病历保存失败：{result.Message}", 
                        "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存病历时发生错误：{ex.Message}", 
                    "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复按钮状态
                btnSave.Enabled = true;
                btnSave.Text = "保存";
            }
        }
        
        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            // 检查是否有未保存的内容
            if (HasUnsavedChanges())
            {
                var result = MessageBox.Show("您有未保存的病历信息，确定要退出吗？", 
                    "确认退出", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    
                if (result == DialogResult.No)
                {
                    return;
                }
            }
            
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
        #endregion

        #region 验证和辅助方法
        /// <summary>
        /// 验证输入数据
        /// </summary>
        /// <returns>验证是否通过</returns>
        private bool ValidateInput()
        {
            // 检查主诉是否为空
            if (string.IsNullOrWhiteSpace(GetTextBoxValue(txtChiefComplaint)))
            {
                MessageBox.Show("请输入主诉信息", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtChiefComplaint.Focus();
                return false;
            }
            
            // 检查现病史是否为空
            if (string.IsNullOrWhiteSpace(GetTextBoxValue(txtPresentIllness)))
            {
                MessageBox.Show("请输入现病史信息", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPresentIllness.Focus();
                return false;
            }
            
            // 检查治疗建议是否为空
            if (string.IsNullOrWhiteSpace(GetTextBoxValue(txtTreatmentAdvice)))
            {
                MessageBox.Show("请输入治疗建议", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtTreatmentAdvice.Focus();
                return false;
            }
            
            return true;
        }
        
        /// <summary>
        /// 获取文本框的实际值（排除提示文本）
        /// </summary>
        /// <param name="textBox">文本框控件</param>
        /// <returns>实际输入的文本</returns>
        private string GetTextBoxValue(TextBox textBox)
        {
            if (textBox.ForeColor == System.Drawing.Color.Gray)
            {
                return string.Empty; // 如果是灰色文字，说明是提示文本
            }
            return textBox.Text.Trim();
        }
        
        /// <summary>
        /// 检查是否有未保存的更改
        /// </summary>
        /// <returns>是否有未保存的内容</returns>
        private bool HasUnsavedChanges()
        {
            return !string.IsNullOrWhiteSpace(GetTextBoxValue(txtChiefComplaint)) ||
                   !string.IsNullOrWhiteSpace(GetTextBoxValue(txtPresentIllness)) ||
                   !string.IsNullOrWhiteSpace(GetTextBoxValue(txtPastHistory)) ||
                   !string.IsNullOrWhiteSpace(GetTextBoxValue(txtAllergyHistory)) ||
                   !string.IsNullOrWhiteSpace(GetTextBoxValue(txtPersonalHistory)) ||
                   !string.IsNullOrWhiteSpace(GetTextBoxValue(txtFamilyHistory)) ||
                   !string.IsNullOrWhiteSpace(GetTextBoxValue(txtPhysicalExam)) ||
                   !string.IsNullOrWhiteSpace(GetTextBoxValue(txtAuxiliaryExam)) ||
                   !string.IsNullOrWhiteSpace(GetTextBoxValue(txtTreatmentAdvice));
        }
        #endregion

        #region API调用方法
        /// <summary>
        /// 调用API保存病历信息
        /// </summary>
        /// <param name="medicalRecord">病历数据</param>
        /// <returns>保存结果</returns>
        private async Task<SaveMedicalRecordResult> SaveMedicalRecordAsync(MedicalRecordData medicalRecord)
        {
            try
            {
                var json = JsonSerializer.Serialize(medicalRecord, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });
                
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync($"{_apiBaseUrl}/api/Medical/CreateMedicalRecord", content);
                
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonSerializer.Deserialize<ApiResponse<string>>(responseContent, new JsonSerializerOptions
                    {
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                    });
                    
                    if (apiResponse?.Code == 200)
                    {
                        return new SaveMedicalRecordResult
                        {
                            Success = true,
                            RecordId = apiResponse.Data ?? "未知",
                            Message = "病历保存成功"
                        };
                    }
                    else
                    {
                        return new SaveMedicalRecordResult
                        {
                            Success = false,
                            Message = apiResponse?.Msg ?? "保存失败"
                        };
                    }
                }
                else
                {
                    return new SaveMedicalRecordResult
                    {
                        Success = false,
                        Message = $"服务器错误：{response.StatusCode}"
                    };
                }
            }
            catch (Exception ex)
            {
                return new SaveMedicalRecordResult
                {
                    Success = false,
                    Message = $"网络错误：{ex.Message}"
                };
            }
        }
        #endregion

        #region 资源释放
        /// <summary>
        /// 释放HTTP客户端资源
        /// </summary>
        private void DisposeHttpClient()
        {
            _httpClient?.Dispose();
        }
        #endregion
    }

    #region 数据模型类
    /// <summary>
    /// 病历数据模型
    /// </summary>
    public class MedicalRecordData
    {
        /// <summary>
        /// 患者ID
        /// </summary>
        public long PatientId { get; set; }
        
        /// <summary>
        /// 患者姓名
        /// </summary>
        public string PatientName { get; set; } = string.Empty;
        
        /// <summary>
        /// 主诉
        /// </summary>
        public string ChiefComplaint { get; set; } = string.Empty;
        
        /// <summary>
        /// 现病史
        /// </summary>
        public string PresentIllness { get; set; } = string.Empty;
        
        /// <summary>
        /// 既往史
        /// </summary>
        public string PastHistory { get; set; } = string.Empty;
        
        /// <summary>
        /// 过敏史
        /// </summary>
        public string AllergyHistory { get; set; } = string.Empty;
        
        /// <summary>
        /// 个人史
        /// </summary>
        public string PersonalHistory { get; set; } = string.Empty;
        
        /// <summary>
        /// 家族史
        /// </summary>
        public string FamilyHistory { get; set; } = string.Empty;
        
        /// <summary>
        /// 体格检查
        /// </summary>
        public string PhysicalExam { get; set; } = string.Empty;
        
        /// <summary>
        /// 辅助检查
        /// </summary>
        public string AuxiliaryExam { get; set; } = string.Empty;
        
        /// <summary>
        /// 治疗建议
        /// </summary>
        public string TreatmentAdvice { get; set; } = string.Empty;
        
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateTime { get; set; }
        
        /// <summary>
        /// 医生姓名
        /// </summary>
        public string Doctor { get; set; } = string.Empty;
    }
    
    /// <summary>
    /// 保存病历结果
    /// </summary>
    public class SaveMedicalRecordResult
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool Success { get; set; }
        
        /// <summary>
        /// 病历编号
        /// </summary>
        public string RecordId { get; set; } = string.Empty;
        
        /// <summary>
        /// 消息
        /// </summary>
        public string Message { get; set; } = string.Empty;
    }
    
    #endregion
}